<template>
  <div class="addGoods">
    <el-form ref="ruleForm" :rules="rules" v-model="goods" label-position="left" label-width="80px">
      <el-row style="margin-top: 10px;">
        <el-form-item label="商品名称">
          <el-input style="width:200px;" placeholder="商品名称" v-model="goods.name"></el-input>
        </el-form-item>
      </el-row>
      <el-row>
        <el-table height="300" :data="addGoodsData" style="width: 100%" border>
          <el-table-column prop label="规格" align="center">
            <template slot-scope="props">
              <el-input
                :class="[props.row.specifications == '' || props.row.specifications == null ? 'highLight' : '']"
                v-if="!props.row.isSave"
                placeholder="请输入商品规格"
                v-model="props.row.specifications"
              ></el-input>
              <span v-if="props.row.isSave">{{props.row.specifications}}</span>
            </template>
          </el-table-column>
          <el-table-column prop label="商品编号" align="center">
            <template slot-scope="props">
              <el-input
                :class="[props.row.goodsNum == '' || props.row.goodsNum == null ? 'highLight' : '']"
                v-if="!props.row.isSave"
                placeholder="请输入商品编号"
                v-model="props.row.goodsNum"
              ></el-input>
              <span v-if="props.row.isSave">{{props.row.goodsNum}}</span>
            </template>
          </el-table-column>
          <el-table-column prop label="单价" align="center">
            <template slot-scope="props">
              <el-input
                :class="[props.row.price == '' || props.row.price == null ? 'highLight' : '']"
                v-if="!props.row.isSave"
                placeholder="请输入商品单价"
                v-model="props.row.price"
              ></el-input>
              <span v-if="props.row.isSave">{{props.row.price}}</span>
            </template>
          </el-table-column>
          <el-table-column prop label="总库存数" align="center">
            <template slot-scope="props">
              <el-input
                :class="[props.row.stock == '' || props.row.stock == null ? 'highLight' : '']"
                v-if="!props.row.isSave"
                placeholder="请输入总库存数"
                v-model="props.row.stock"
              ></el-input>
              <span v-if="props.row.isSave">{{props.row.stock}}</span>
            </template>
          </el-table-column>
          <el-table-column prop label="低库存数" align="center">
            <template slot-scope="props">
              <el-input
                :class="[props.row.lowWarnStock == '' || props.row.lowWarnStock == null ? 'highLight' : '']"
                v-if="!props.row.isSave"
                placeholder="请输入低库存数"
                v-model="props.row.lowWarnStock"
              ></el-input>
              <span v-if="props.row.isSave">{{props.row.lowWarnStock}}</span>
            </template>
          </el-table-column>
          <el-table-column prop label="库存备注" align="center">
            <template slot-scope="props">
              <el-input v-if="!props.row.isSave" placeholder="请输入库存备注" v-model="props.row.notes"></el-input>
              <span v-if="props.row.isSave">{{props.row.notes}}</span>
            </template>
          </el-table-column>
          <el-table-column prop label="操作" align="center" width="200">
            <template slot-scope="scope">
              <span
                v-if="!scope.row.isSave"
                class="el-tag el-tag--info el-tag--small"
                style="cursor: pointer;"
                @click="save(scope.row, scope.$index)"
                size="mini"
              >保存</span>
              <span
                v-if="!scope.row.isSave"
                class="el-tag el-tag--primary el-tag--small"
                style="cursor: pointer;"
                @click="cancel(scope.row)"
                size="mini"
              >取消</span>
              <span
                v-if="scope.row.isSave"
                class="el-tag el-tag--info el-tag--small"
                style="cursor: pointer;"
                @click="modify(scope.row)"
                size="mini"
              >修改</span>
              <span
                v-if="scope.row.isSave"
                class="el-tag el-tag--primary el-tag--small"
                style="cursor: pointer;"
                @click="del(scope.row)"
                size="mini"
              >删除</span>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row style="text-align:right;margin: 10px 0">
        <el-button size="large" type="primary" icon="el-icon-plus" @click="add"></el-button>
      </el-row>
      <el-row>
        <el-table :data="goodsInfo" style="width: 100%" border>
          <el-table-column prop label="规格" align="center">
            <template slot-scope="props">
              <el-cascader
                v-model="goods.kind"
                placeholder="按分类筛选"
                :show-all-levels="false"
                :clearable="true"
                :props="{children: 'list',label: 'catName',value: 'catId',checkStrictly: true}"
                :options="options"
                @expand-change="handleChange"
              ></el-cascader>
            </template>
          </el-table-column>
          <el-table-column prop label="供应商" align="center">
            <template slot-scope="props">
              <el-select
                v-model="goods.supplier"
                filterable
                remote
                reserve-keyword
                placeholder="请输入供应商"
                :remote-method="remoteMethodSupplier"
                :loading="loading2"
              >
                <el-option
                  v-for="item in supplier"
                  :key="item.brandId"
                  :label="item.brandName"
                  :value="item.brandId"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop label="品牌搜索" align="center">
            <template slot-scope="props">
              <el-select
                v-model="goods.brand"
                filterable
                remote
                reserve-keyword
                placeholder="请输入品牌"
                :remote-method="remoteMethodBrand"
                :loading="loading1"
              >
                <el-option
                  v-for="item in brand"
                  :key="item.brandId"
                  :label="item.brandName"
                  :value="item.brandId"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop label="详细图" align="center">
            <template slot-scope="props">
              <el-upload
                :style="{height:'70px'}"
                :show-file-list="false"
                :on-success="handleAvatarSuccess1"
                :before-upload="beforeAvatarUpload"
                :on-error="error"
                class="avatar-uploader"
                accept="image/*"
                action="http://192.168.1.68:18082/user/upload/image"
                list-type="picture-card"
              >
                <div
                  class="add"
                  style="position: relative;width:70px;height:70px;border:0.5px solid #ccc;"
                >
                  <div
                    class="box"
                    style="margin:2px 0px 0px 2px;width:20px;height:20px;border:0.5px solid #ccc;"
                  ></div>
                  <img
                    style="position:absolute;left:0px;top:0px;"
                    width="70"
                    height="70"
                    :src="goods.goodsImg"
                    alt
                  />
                </div>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column prop label="缩略图" align="center">
            <template slot-scope="props">
              <el-upload
                :style="{height:'70px'}"
                :show-file-list="false"
                :on-success="handleAvatarSuccess2"
                :before-upload="beforeAvatarUpload"
                :on-error="error"
                class="avatar-uploader"
                accept="image/*"
                action="http://192.168.1.68:18082/user/upload/image"
                list-type="picture-card"
              >
                <div
                  class="add"
                  style="position: relative;width:70px;height:70px;border:0.5px solid #ccc;"
                >
                  <div
                    class="box"
                    style="margin:2px 0px 0px 2px;width:20px;height:20px;border:0.5px solid #ccc;"
                  ></div>

                  <img
                    style="position:absolute;left:0px;top:0px;"
                    width="70"
                    height="70"
                    :src="goods.thumbnail"
                    alt
                  />
                </div>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column prop label="商品描述" align="center">
            <template slot-scope="props">
              <el-input type="textarea" placeholder="请输入商品描述" v-model="props.row.notes"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop label="商品关键字" align="center">
            <template slot-scope="props">
              <el-input placeholder="请输入商品关键字" v-model="props.row.goodsSeoKeywords"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row style="text-align:center;margin-top:10px;">
        <el-button type="primary" @click="submit">提交</el-button>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { getSupplierList } from "@/api/jxc/supplier.js";
import { findBrandByName, getGoodsKindList } from "@/api/jxc/goods.js";
export default {
  name: "addGoods",
  data() {
    var checkPrice = (rule, value, callback) => {
      if (value > 0) {
        return callback();
      } else {
        return callback(new Error("价格不能为负数"));
      }
    };
    var checkStock = (rule, value, callback) => {
      if (value > 0) {
        return callback();
      } else {
        return callback(new Error("总库存数不能为负数"));
      }
    };
    var checkLowerStock = (rule, value, callback) => {
      if (value > 0) {
        return callback();
      } else {
        return callback(new Error("低库存数不能为负数"));
      }
    };
    return {
      rules: {
        specifications: [
          { required: true, message: "规格不能为空", trigger: "blur" }
        ],
        goodsNum: [
          { required: true, message: "商品编号不能为空", trigger: "blur" },
          { type: "number", message: "商品编号必须为数字" }
        ],
        price: [
          { required: true, message: "单价不能为空", trigger: "blur" },
          { validator: checkPrice, trigger: "blur" }
        ],
        stock: [
          { required: true, message: "总库存数不能为空", trigger: "blur" },
          { validator: checkStock, trigger: "blur" }
        ],
        lowWarnStock: [
          { required: true, message: "低库存数不能为空", trigger: "blur" },
          { validator: checkLowerStock, trigger: "blur" }
        ]
      },
      goods: {
        name: "",
        kind: "",
        supplier: "",
        brand: ""
      },
      brand: [],
      supplier: [],
      noInput: true,
      addGoodsData: [],
      options: [],
      loading1: false,
      loading2: false,
      goodsInfo: [
        {
          kind: "",
          supplier: "",
          brand: "",
          thumbnail: "",
          goodsImg: "",
          goodsSeoKeywords: "",
          notes: ""
        }
      ]
    };
  },
  created() {
    getGoodsKindList().then(
      res => {
        console.log("商品分类级联res", res);
        this.options = res.data;
      },
      err => {}
    );
  },
  methods: {
    error(err, file, fileList) {
      console.log(err, file, fileList);
    },
    handleAvatarSuccess1(res, file) {
      console.log("上传成功res", res);
      console.log("上传成功file", file);
      this.goods.goodsImg = res.data;
    },
    handleAvatarSuccess2(res, file) {
      console.log("上传成功res", res);
      console.log("上传成功file", file);
      this.goods.thumbnail = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!');
      // }
      // return isJPG && isLt2M;
    },
    modify(row) {
      row.isSave = false;
    },
    del(row, index) {
      this.addGoodsData.splice(index, 1);
      this.$notify({
        type: "success",
        message: "删除成功"
      });
    },
    submit() {},
    remoteMethodBrand(query) {
      if (query !== "") {
        this.goods.brand = query;
        this.loading1 = true;
        findBrandByName({
          currentPage: 1,
          pageSize: 10,
          brandName: query
        }).then(
          res => {
            this.brand = res.data.list;
            console.log("this.options", this.optionsNum);
            this.loading1 = false;
          },
          err => {}
        );
      } else {
        this.optionsNum = [];
      }
    },
    remoteMethodSupplier(query) {
      if (query !== "") {
        this.goods.supplier = query;
        this.loading2 = true;
        getSupplierList({
          currentPage: 1,
          pageSize: 10,
          providerName: query
        }).then(
          res => {
            this.supplier = res.data.list;
            console.log("this.options", this.optionsNum);
            this.loading2 = false;
          },
          err => {}
        );
      } else {
        this.optionsNum = [];
      }
    },
    handleChange(row) {
      this.goods.kind = row[row.length - 1];
    },
    save(row, index) {
      console.log(row, index);
      if (
        row.specifications == "" ||
        row.specifications == null ||
        row.goodsNum == "" ||
        row.goodsNum == null ||
        row.price == "" ||
        row.price == null ||
        row.stock == "" ||
        row.stock == null ||
        row.lowWarnStock == "" ||
        row.lowWarnStock == null
      ) {
        return;
      }
      row.isSave = true;
      this.$notify({
        type: "success",
        message: "保存成功"
      });

      console.log(this.addGoodsData);
      // this.addGoodsData.forEach((e, i) => {
      //     if(index == i){
      //         e.isSave = true;
      //     }
      // });
    },
    cancel() {},
    add() {
      if (this.addGoodsData.length > 0) {
        this.addGoodsData.forEach(e => {
          if (!e.isSave) {
            this.$notify({
              type: "warning",
              message: "请先保存当前编辑项"
            });
            throw new Error("请先保存当前编辑项");
          }
        });
      }
      this.addGoodsData.push({
        isSave: false,
        specifications: "",
        goodsNum: "",
        price: "",
        stock: "",
        lowWarnStock: "",
        notes: "",
        goodsNum: ""
      });
    }
  }
};
</script>

<style lang="less" scoped>
/deep/.highLight .el-input__inner {
  border: 1px solid red;
}
/deep/.el-upload--picture-card {
  width: 70px !important;
  height: 70px !important;
  border: none;
}
</style>